package com.winit.requirement.service.impl;

import com.winit.common.base.bean.ExecuteResult;
import com.winit.common.base.web.BaseController;
import com.winit.commons.util.SeqGenerate;
import com.winit.requirement.mapper.ReqReportFormMapper;
import com.winit.requirement.model.ReqReportForm;
import com.winit.requirement.service.ReqReportFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wanglin on 2018/4/16.
 */
@Service
public class ReqReportFormImpl implements ReqReportFormService {

    @Autowired
    ReqReportFormMapper reqReportFormMapper;

    @Value("${req.report.form.path}")
    String reqReportFormPath;

    @Override
    public ReqReportForm saveReqReportForm(MultipartFile multipartFile, String reqId) throws IOException {
        String fileName = multipartFile.getOriginalFilename();
        String rfFileId = SeqGenerate.createId("RRF");
        String basePath = reqReportFormPath+reqId;
        File directory = new File(basePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        Integer count=1;
        boolean isTrue=true;
        do {
            int FileNameCount;
            Map map = new HashMap<>();
            map.put("fileName",fileName);
            map.put("reqId",reqId);
            FileNameCount=reqReportFormMapper.getFileNameCount(map);
            if(FileNameCount!=0){
                fileName=this.getFilename(multipartFile.getOriginalFilename(),count);
                count++;
            }else{
                isTrue=false;
            }

        }while (isTrue);


        File targetFile = new File(directory, fileName);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
//                log.error(e.getMessage(), e);
                throw e;
            }
        }
        try {
            multipartFile.transferTo(targetFile);
        } catch (IOException e) {
//            log.error(e.getMessage(), e);
            throw e;
        }
        ReqReportForm reqReportForm=new ReqReportForm();
        reqReportForm.setCreateTime(new Date());
        reqReportForm.setFileName(fileName);
        reqReportForm.setFilePath("/"+reqId+"/"+targetFile.getName());
        reqReportForm.setId(rfFileId);
        reqReportForm.setReqId(reqId);
        reqReportFormMapper.insert(reqReportForm);
        return reqReportForm;
    }

    //下载文件
    @Override
    public ExecuteResult<Object> getPrototype(String fileId) {
        ExecuteResult<Object> er = new ExecuteResult<>();
        ReqReportForm reqReportForm = reqReportFormMapper.selectByPrimaryKey(fileId);
        if(null==reqReportForm){
            er.setCode(BaseController.REQUEST_ERROR);
            er.setDesc("sys err,file does not exist");
        }else{
            File file = new File(reqReportFormPath+reqReportForm.getFilePath());
            er.setData(file);
        }

        return er;
    }

    @Override
    public ExecuteResult getReqReportFormList(String reqId){
        ExecuteResult er=new ExecuteResult();
        er.setData(reqReportFormMapper.getReqId(reqId));
        return er;
    }

    @Override
    public ExecuteResult deleteReqReportForm(String fileId) {
        ExecuteResult er = new ExecuteResult<>();
        ReqReportForm reqReportForm = reqReportFormMapper.selectByPrimaryKey(fileId);
        if(null==reqReportForm){
            er.setCode(BaseController.REQUEST_ERROR);
            er.setDesc("sys err,file does not exist");
            return er;
        }
        String reqId=reqReportForm.getReqId();
        File file = new File(reqReportFormPath+reqReportForm.getFilePath());
        if(file.delete()){
            reqReportFormMapper.deleteByPrimaryKey(fileId);
        }
        file = new File(reqReportFormPath+"/"+reqId);
        File[] listFiles = file.listFiles();
        if(listFiles.length == 0){
            file.delete();
        }
        return er;
    }


    /**
     * 获取文件名
     * @param fileName
     * @param count
     * @return
     */
    private String  getFilename(String fileName,Integer count){
        fileName=fileName.indexOf(".")!=-1? fileName.substring(0, fileName.lastIndexOf("."))+count.toString()+"."+fileName.substring(fileName.lastIndexOf(".") + 1):fileName+count.toString();
        return fileName;
    }
}



